class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def longestZigZag(self, root):
        self.max_value = 0

        def search(node, left, right):
            self.max_value = max(self.max_value, left + 1, right + 1)
            if node.left:
                search(node.left, right + 1, 0)
            if node.right:
                search(node.right, 0, left + 1)

        search(root, 0, 0)
        return self.max_value - 1